var express = require('express');
var Msdb = require("../../../db/Mysqldb.js")
var router = express.Router()   //可使用 express.Router 类创建模块化、可挂载的路由句柄

var db = new Msdb()
var getTime=()=>{
    return new Date(new Date().getTime()+8 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' ');//获取系统时间并转为数据库接受的格式
}

router.post("/getNotices",async function(req,res){//获取通知
    var result={}
    var data=req.body
    var notices=await db.query(`SELECT * FROM notice LIMIT ? OFFSET ?`,[data.pageSize,data.offset])
    const [countResult] = await db.query(`SELECT COUNT(*) AS total FROM notice`);//统计总数
    result={
        code:200,
        msg:"查询成功",
        data:notices,
        total:countResult.total
    }
    res.send(JSON.stringify(result))
})

router.post("/getNoticeById",async function(req,res){//通过id获取具体的通知
    var data=req.body
    var notice=await db.query(`SELECT * FROM notice WHERE id=?`,[data.id])
    res.send(JSON.stringify(notice[0]))
})

router.post("/deleteById",async function(req,res){//通过id删除具体的通知
    var result={}
    var data=req.body
    if(req.auth.role_id==1||req.auth.role_id==3){//权限校验通过
        await db.query(`DELETE FROM notice WHERE id=?`,[data.id])
        result={
            code:200,
            msg:"删除成功"
        }
        var sql_words=`DELETE FROM notice WHERE id=${data.id}`
        await db.query(`INSERT INTO operation_log (user_id,sql_words,time) VALUES (?,?,?);`,[req.auth.user_id,sql_words,getTime()])//插入删除通知日志
    } else {
        result={
            code:201,
            msg:"当前账号不为超级管理员/系统运维专员,不得删除通知！"
        }
    }
    res.send(JSON.stringify(result))
})

router.post("/publishNotice",async function(req,res){//发布通知
    var result={}
    var data=req.body
    if(req.auth.role_id==1||req.auth.role_id==3){//权限校验通过
        await db.query(`INSERT INTO notice (content,create_time,create_id,type,level,title) VALUES (?,?,?,?,?,?)`,[data.notice.content,getTime(),req.auth.user_id
            ,0,0,data.notice.title
        ])
        result={
            code:200,
            msg:"发布成功"
        }
        var sql_words=`INSERT INTO notice (content,create_time,create_id,type,level,title) VALUES (${data.notice.content},${getTime()},${req.auth.user_id}
        ,0,0,${data.notice.title})`
        await db.query(`INSERT INTO operation_log (user_id,sql_words,time) VALUES (?,?,?);`,[req.auth.user_id,sql_words,getTime()])//插入新增通知日志
    } else {
        result={
            code:201,
            msg:"当前账号不为超级管理员/系统运维专员,不得发布通知！"
        }
    }
    res.send(JSON.stringify(result))
})

module.exports = router